<template>
  <div class="app-container">
    <div class="jbl-carousel">
      <el-carousel height="2.3rem">
        <el-carousel-item class="jbl-carousel-item" v-for="(item,index) in banner" :key="index">
          <img class="item-img" :src="item.imgUrl" @click="handleClick(item)"/>
        </el-carousel-item>
      </el-carousel>
    </div>
    <div style="margin-top:10px">
        <el-row style="margin-bottom:10px" type="flex" justify="space-between" align="middle">
          <div>
            <el-radio-group
            style="margin-right:20px"
            size="small"
            v-model="date"
            @change="changeDate">
              <el-radio-button
                v-for="item in timeList"
                :label="item.id"
                :key="item.id">
                {{item.name}}
              </el-radio-button>
            </el-radio-group>
            <el-date-picker
              size="small"
              v-model="time"
              :clearable="false"
              type="daterange"
              value-format="timestamp"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="changeTime">
            </el-date-picker>
          </div>
          <div class="down">
            <el-button type="text" @click="handlePrint">
              <i class="el-icon-download"></i>
            </el-button>
          </div>
        </el-row>
        <div style="width:100%" ref="imageDom">
          <div class="canvas-box">
            <div style="background:#fff" class="statistics-list" v-for="(item,index) in statistics" :key="index">
              <p class="list-title">{{item.name}} <span>（{{timeFrame}}）</span></p>
              <!-- <span class="card-panel-num" v-if="generate">{{item.price}}</span> -->
              <div class="card-panel-num">
                <count-to :start-val="0" :end-val="item.price" :decimals="index===0?2:0" :duration="1500"/>
              </div>
              <div class="list-bottom" v-if="type!=='5'">
                  <div class="list_p">
                    环比：
                    <div class="p_span" :style="{'color':item.h>0?'#f64343':'#42b983'}">
                    {{item.h}}%
                      <i v-if="item.h>0 && item.t != 0" class="el-icon-top"></i>
                      <i v-if="item.h<0 && item.t != 0" class="el-icon-bottom"></i>
                    </div>
                    <div class="tooltip">与上一个日/周/月对比</div>
                  </div>
                  <div class="list_p" style="margin-left:10px">
                    同比：
                    <div class="p_span" :style="{'color':item.t>0?'#f64343':'#42b983'}">
                      {{item.t}}%
                      <i v-if="item.t>0 && item.t != 0" class="el-icon-top"></i>
                      <i v-if="item.t<0 && item.t != 0" class="el-icon-bottom"></i>
                    </div>
                    <div class="tooltip">与上一年同期对比</div>
                  </div>
              </div>
              <div v-else></div>
            </div>
          </div>
          <div class="stream">
            <div class="left" style="background:#fff">
              <p>流水数据 <span>（{{timeFrame}}）</span></p>
              <table class="jbl-table" border="0" cellspacing="0" align="center">
                <tr>
                  <th>指标</th>
                  <th>合计</th>
                </tr>
                <tr>
                  <td>销售总额</td>
                  <td>{{streamData.sellSum}}</td>
                </tr>
                <tr>
                  <td>生成订单数</td>
                  <td>{{streamData.orderNum}}</td>
                </tr>
                <tr>
                  <td>支付成功总额（¥）</td>
                  <td>{{streamData.paySuccessSum}}</td>
                </tr>
                <tr>
                  <td>支付成功订单数</td>
                  <td>{{streamData.paySuccessNum}}</td>
                </tr>
                <tr>
                  <td>优惠券抵扣金额（¥）</td>
                  <td>{{streamData.couponSum}}</td>
                </tr>
                <tr>
                  <td>退款金额（¥）</td>
                  <td>{{streamData.refundSum}}</td>
                </tr>
              </table>
            </div>
            <div class="left" style="background:#fff">
              <p>课程销售额 <span>（{{timeFrame}}）</span></p>
              <!-- <div id="echart" style="background:#fff;padding:16px;margin:32px 0; width:100%;height:100%">
              </div> -->
              <chart :options="options" width="100%" height="385px"></chart>
            </div>
          </div>
        </div>
    </div>
  </div>
</template>

<script>
import CountTo from 'vue-count-to'
import chart from '@/components/Charts/Keyboard'
import html2canvas from 'html2canvas'
import { randomString } from '@/utils'
import {
  getBannerList,
  getOrderReport,
  courseReport,
  getOrderSellReport,
  getViewReport,
  getCollectionReport,
  getShareReport
} from '@/api/home'

export default {
  name: 'Home',
  components: { chart, CountTo },
  data() {
    return {
      generate: false,
      banner: [
        // "https://ossdev0.jiabala.com/kLrzkyDGExLuB",
        // "https://ossdev0.jiabala.com/kLrzkyDGExLuB",
        // "https://ossdev0.jiabala.com/kLrzkyDGExLuB",
      ],
      paramsList: {
        typeId: 4,
        enable: 1,
        belongToPage: 2
      },
      type: '', // 条件类型(1.今日,2.本周,3.本月,4.上月,5.任意时间)
      date: '', // 本周 本月 上月
      startDate: null,
      endDate: null,
      time: [], // 日期时间选择器
      startTime: null,
      endTime: null,
      timeList: [],
      streamData: {},
      options: {},
      statistics: [
        {
          name: '销售额',
          price: 0,
          h: '0',
          t: '0'
        },
        {
          name: '机构访问量',
          price: 0,
          h: '0',
          t: '0'
        },
        {
          name: '课程分享数',
          price: 0,
          h: '0',
          t: '0'
        },
        {
          name: '课程收藏量',
          price: 0,
          h: '0',
          t: '0'
        }
      ],
      num: 0
    }
  },
  computed: {
    timeFrame() {
      return `${this.$options.filters.parseTime(this.startDate, '{y}-{m}-{d}')} ~ ${this.$options.filters.parseTime(this.endDate, '{y}-{m}-{d}')}`
    }
  },
  created() {
    this.setTimeData()
  },
  mounted() {
    getBannerList(this.paramsList).then((res) => {
      this.banner = res.data
    })
  },
  methods: {
    handleClick(item) {
      // window.open(item.h5Link, '_blank')
      const { href } = this.$router.resolve({
        name: 'picView',
        params: {
          url: 'https://ossdev0.jiabala.com/EAkBTz6ZHmWhJ'
        }
      })
      localStorage.setItem('imgurl', item.h5Link)
      window.open(href, '_blank')
    },
    changeDate(val) {
      const t = val.split(',')
      this.startDate = +t[0]
      this.endDate = +t[1]
      this.type = +t[2]
      this.time = [+t[0], +t[1]]
      this.init()
    },
    changeTime(time) {
      this.date = null
      this.startDate = time[0]
      this.endDate = time[1] + 86399000
      this.type = '5'
      this.init()
    },
    handlePrint() {
      // window.print()
      this.generate = true
      window.scrollTo(0, 0)
      const loading = this.$loading({
        lock: true,
        text: '努力生成中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      setTimeout(() => {
        // this.$refs[formName].resetFields()
        const canvasBox = this.$refs.imageDom
        // const canvasBox= cloneDom.cloneNode(true);
        // document.body.appendChild(canvasBox)
        this.$nextTick(() => {
          // 手动创建一个 canvas 标签
          const canvas = document.createElement('canvas')
          // 获取父标签，意思是这个标签内的 DOM 元素生成图片
          // 获取父级的宽高
          const width = parseInt(window.getComputedStyle(canvasBox).width)
          const height = parseInt(window.getComputedStyle(canvasBox).height)

          // let {width, height} = canvasBox.getBoundingClientRect();
          const dpr = window.devicePixelRatio || 1
          // 宽高 * 2 并放大 2 倍 是为了防止图片模糊
          canvas.width = width * dpr
          canvas.height = height * dpr
          canvas.style.width = width + 'px'
          canvas.style.height = height + 'px'
          const context = canvas.getContext('2d')
          context.scale(dpr, dpr)
          const rectObject = canvasBox.getBoundingClientRect()
          const eleft = rectObject.left
          const etop = rectObject.top
          context.translate(-eleft, -etop)
          // const sidebarStatus = Cookies.get('sidebarStatus') === '0' ? 2 : 5
          html2canvas(canvasBox,
            {
              useCORS: true, // 【重要】开启跨域配置
              // allowTaint: true, // 允许跨域图片
              tainttest: true, // 检测每张图片都已经加载完成
              logging: false,
              ...canvas,
              // scrollY: 0,
              // scrollX: 0,
              letterRendering: true,
              backgroundColor: '#F7F8FC' // null 表示设置背景为透明色
            }
          ).then(canvas => {
            // 转成图片，生成图片地址
            loading.close()
            const imgUrl = canvas.toDataURL('image/png')
            const link = document.createElement('a')
            link.style.display = 'none'
            link.href = imgUrl
            link.download = `数据统计_${randomString(5)}`
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
            // document.body.removeChild(canvasBox)
            this.generate = false
            // console.log(imgUrl)
          })
        })
      }, 500)
    },
    // 获得某月的天数
    getMonthDays(myMonth, nowYear) {
      var monthStartDate = new Date(nowYear, myMonth, 1)
      var monthEndDate = new Date(nowYear, myMonth + 1, 1)
      var days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24)
      return days
    },
    setTimeData() {
      const end = new Date()
      const start = new Date()
      const nowDayOfWeek = start.getDay() // 今天本周的第几天
      const nowDay = start.getDate() // 当前日
      const nowMonth = start.getMonth() // 当前月
      const nowYear = start.getFullYear() // 当前年
      const lastMonthDate = new Date() // 上月日期
      lastMonthDate.setDate(1)
      lastMonthDate.setMonth(lastMonthDate.getMonth() - 1)
      const lastYear = lastMonthDate.getYear()
      const lastMonth = lastMonthDate.getMonth()
      // 上月开始时间
      const monthStart = new Date(nowYear, lastMonth, 1)
      // 上月结束时间
      const monthEnd = new Date(nowYear, lastMonth, this.getMonthDays(lastMonth, nowYear))
      // 今天0点
      // const todayStart = new Date(new Date(start.toLocaleDateString()).getTime())
      const todayStart = new Date(new Date(new Date().getTime()).setHours(0,0,0,0));

      // 今天23点
      const todayEnd = new Date(new Date(start.toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1)
      // 本周第一天
      const weekStart = new Date(start.getFullYear(), nowMonth, nowDay + 1 - nowDayOfWeek || 7)
      // 本周最后一天
      const weekEnd = new Date(start.getFullYear(), nowMonth, nowDay + 7 - nowDayOfWeek || 7)
      // 本月
      start.setTime(new Date(start.getFullYear(), start.getMonth(), 1))
      this.timeList = [
        {
          name: '今日',
          id: `${todayStart.valueOf()},${new Date(end).valueOf()},1`,
          value: '1'
        },
        {
          name: '本周',
          value: '2',
          id: `${weekStart.valueOf()},${weekEnd.valueOf() + 24 * 60 * 60 * 1000 - 1},2`
        },
        {
          name: '本月',
          value: '3',
          id: `${new Date(start).valueOf()},${new Date(end.getFullYear(), end.getMonth() + 1, 0).valueOf()},3`
        },
        {
          name: '上月',
          value: '4',
          id: `${monthStart.valueOf()},${monthEnd.valueOf()},3`
        }
      ]
      this.date = `${todayStart.valueOf()},${new Date(end).valueOf()},1`
      this.time = [todayStart.valueOf(),new Date(end).valueOf()]
      this.startDate = todayStart.valueOf()
      this.endDate = new Date(end).valueOf()
      this.type = '1'
      this.init()
    },
    numFomatter(val) {
      const index = val ? val.lastIndexOf('%') : 0
      const n = val ? val.slice(0, index) : 0
      return +n
    },
    init() {
      const param = {
        'businessId': this.$store.getters.businessId,
        'startDate': `${this.startDate}`,
        'endDate': `${this.endDate}`,
        'type': this.type // 条件类型(1.今日,2.本周,3.本月,4.上月,5.任意时间)
      }
      getOrderSellReport(param).then(res => {
        const { sum, hb, tb } = res.data
        this.statistics.splice(0, 1, {
          name: '销售额',
          price: sum || 0,
          h: this.numFomatter(hb),
          t: this.numFomatter(tb)
        })
      })
      getViewReport(param).then(res => {
        const { sum, hb, tb } = res.data
        this.statistics.splice(1, 1, {
          name: '机构浏览量',
          price: sum || 0,
          h: this.numFomatter(hb),
          t: this.numFomatter(tb)
        })
      })
      getShareReport(param).then(res => {
        const { sum, hb, tb } = res.data
        this.statistics.splice(2, 1, {
          name: '课程分享数',
          price: sum || 0,
          h: this.numFomatter(hb),
          t: this.numFomatter(tb)
        })
      })
      getCollectionReport(param).then(res => {
        const { sum, hb, tb } = res.data
        this.statistics.splice(3, 1, {
          name: '课程收藏量',
          price: sum || 0,
          h: this.numFomatter(hb),
          t: this.numFomatter(tb)
        })
      })
      getOrderReport({
        'businessId': this.$store.getters.businessId,
        'startDate': this.startDate,
        'endDate': this.endDate
      }).then(res => {
        this.streamData = res.data
      })
      courseReport({
        'businessId': this.$store.getters.businessId,
        'startDate': this.startDate,
        'endDate': this.endDate
      }).then(res => {
        const x = []; const y = []
        res.data.forEach(i => {
          x.push(i.x)
          y.push(i.y)
        })
        this.$nextTick(() => {
          this.options = {
            backgroundColor: '#fff',
            // title: {
            //   text: ''
            // },
            tooltip: {},
            xAxis: {
              axisLine: {
                show: false // 隐藏坐标轴线
              },
              type: 'category',
              splitLine: { show: false },
              symbol: 'none', // 这句就是去掉点的
              data: x,
              axisTick: {
                alignWithLabel: true
              },
              axisLabel: {
                interval: 0
                // formatter(value) {
                //   return value.split('').join('\n')
                // }
                // rotate: 40
              },
              nameTextStyle: {
                fontStyle: 'oblique',
                fontSize: 12,
                align: 'center'
              }
            },

            yAxis: {
              axisLine: {
                show: false
              }
              // data: y
            },
            dataZoom: [
              {
                start: 0,
                type: 'inside',
                show: false, // 是否显示
                end: 50
              },
              {
                start: 0,
                backgroundColor: 'rgba(196, 229, 252, 0)',
                fillerColor: 'rgba(196, 221, 255, 0.4)'
              }
            ],
            series: [
              {
                name: '课程销售额',
                type: 'bar',
                data: y,
                color: ['#1890ff'],
                barWidth: '60%',
                lineStyle: {
                  width: 4
                },
                barMaxWidth: 40,
                cursor: 'pointer'
              }
            ]
          }
        })
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.jbl-carousel{
  margin-top:10px;
  // height: 2.3rem;
  overflow: hidden;
  border-radius: 20px;
  box-sizing: border-box;
  /deep/.el-carousel__button{
    width:8px;
    height:8px;
    background:rgba(255,255,255,1);
    opacity:0.5;
    border-radius:4px;
  }
  /deep/.is-active .el-carousel__button{
    width:20px;
    height:8px;
    background:#ff7323;
    opacity:1;
    border-radius:4px;
  }
  .jbl-carousel-item{
    width: 100%;
    overflow: hidden;
    .item-img{
      width: 100%;
      object-fit: cover;
    }
  }
}
.mainInfo {
  display: flex;
  justify-content: center;
  padding-top: 0.5rem;
  .manImg {
    width: 3.84rem;
    height: 4.5rem;
  }
  .building-word {
    h3 {
      // width:100%;
      height: 0.5rem;
      font-size: 0.36rem;
      font-weight: 600;
      line-height: 0.4rem;
      color: rgba(118, 126, 145, 1);
      opacity: 1;
    }
    div {
      // width: 100%;
      height: 1.08rem;
      p {
        font-size: 0.2rem;
        font-weight: 400;
        color: rgba(184, 186, 206, 1);
        opacity: 1;
      }
    }
  }
}

.el-button{
    font-size: 22px;
  }
  .stream{
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    // height: 475px;
    .left{
      padding: 20px;
      width:49%;
      // background: #fff;
      box-sizing: border-box;
      transition: all .3S ease-in-out;
      &:hover{
       box-shadow: 0px 0px 10px rgba(129, 129, 129, 0.3);
      }
      >p{
        margin:15px 20px;
        font-size: 18px;
        >span{
          font-size: 14px;
          color: rgb(99, 99, 99);
        }
      }
      .jbl-table{
        width: 100%;
        // height: 100%;
        border-left: 1px solid #dfe6ec;
        border-bottom: 1px solid #dfe6ec;
        tr{
          transition: all .2s ease-in-out;
          &:hover{
            background: #e6f3ff;
          }
        }
        th{
          width: 50%;
          font-size: 16px;
        }
        td{
          font-size: 14px;
        }
        th,td{
          line-height: 50px;
          text-align: center;
          border-top: 1px solid #dfe6ec;
          border-right: 1px solid #dfe6ec;
        }
      }
    }
  }
  .canvas-box{
    margin-bottom:10px;
    display: flex;
    justify-content: space-between;
    .statistics-list{
      cursor: pointer;
      padding: 15px;
      display: flex;
      flex-flow: column;
      justify-content: space-between;
      align-items: center;
      width: 23.5%;
      min-width: 245px;
      height: 150px;
      // background: #fff;
      transition: all .3S ease-in-out;
      &:hover{
        box-shadow: 0px 0px 10px rgba(129, 129, 129, 0.3);
      }
      .list-title{
        margin:0;
        font-size: 16px;
        >span{
          font-size: 12px;
          color: rgb(99, 99, 99);
        }
      }
      .card-panel-num{
        font-size: 30px;
        font-weight: 600;
      }
      .list-bottom{
        display: flex;
        .list_p{
          position: relative;
          display: flex;
          margin: 0;
          font-size: 12px;
          &:hover .tooltip{
            display: block;
          }
          .tooltip{
            display: none;
            position: absolute;
            bottom: -35px;
            left: -50px;
            padding: 6px 10px;
            width: 170px;
            text-align: center;
            font-size: 12px;
            letter-spacing: 3px;
            color: #fff;
            background: rgba(0,0,0,.7);
            border-radius: 60px;
            transition: all .3s ease-in-out;
            &::after{
              position: absolute;
              top: -6px;
              left: 50%;
              display: block;
              content: '';
              width: 0;
              height: 0;
              border-bottom: 6px solid rgba(0,0,0,.7);
              border-right: 6px solid transparent;
              border-left: 6px solid transparent;
            }
          }
          .p_span{
            display: flex;
            font-size: 12px;
            font-weight: 600;
          }
        }
      }
    }
  }
</style>
